<?php
/**
 * Created by PhpStorm.
 * User: Hua Wei
 * Date: 2020/2/19
 * Time: 15:22
 */
namespace app\admin\controller;
use think\swoole\Server as swoole_server;
use org\Redis;
error_reporting(0);
class Swoole extends swoole_server
{
    protected $host = '0.0.0.0';//监听所有地址
    protected $port = 9501;//监听9501端口
    protected $serverType = 'socket';
    protected $option = [
        'worker_num'=> 4, //设置启动的Worker进程数
        'daemonize'    => true, //守护进程化（上线改为true）
        'backlog'    => 128, //Listen队列长度
        'dispatch_mode' => 2, //固定模式，保证同一个连接发来的数据只会被同一个worker处理
        //心跳检测：每60秒遍历所有连接，强制关闭10分钟内没有向服务器发送任何数据的连接
        'heartbeat_check_interval' => 65,
        'heartbeat_idle_time' => 650
    ];


    //建立连接时回调函数
    public function onOpen($server,$request){

        $fd = $request->fd;//客户端标识
        $wxapp_id = $request->get['store_id'];//客户端传递的用户store_id
        if (!$wxapp_id) {
            $arr = ['status'=>2,'message'=>'参数错误'];
            $server->push($fd, json_encode($arr));
            $server->close($fd);
            return;
        }

        //绑定fd和wxapp_id
        $redis = $this->newRedis();

        $redis -> hSet('swoole_fd_wxapp_id',$fd,$wxapp_id);

        $num = $this->getNum($fd);
        $arr = ['status'=>1,'message'=>'成功','data'=>$num];

        $server->push($fd, json_encode($arr));

        //echo "{$wxapp_id}连接成功\n";
    }

    //接收数据时回调函数
    public function onMessage($server,$frame)
    {
        $fd = $frame->fd;
        $type = $frame->data;

        $num = $this->getNum($fd);

        $arr = ['status'=>1,'message'=>'成功','data'=>$num];
        if($type=='HeartBeat'){
            $server->push($fd, json_encode($arr));
        }

    }

    //连接关闭时回调函数
    public function onClose($server,$fd)
    {
        //删除用户在线
        $redis = $this->newRedis();
        $wxapp_id   = $redis -> hGet('swoole_fd_wxapp_id',$fd);

        if ($wxapp_id) {
            $redis -> hDel('swoole_fd_wxapp_id',$fd);
        }
    }

    public function getNum($fd){

        $redis = $this->newRedis();
        $wxapp_id   = $redis -> hGet('swoole_fd_wxapp_id',$fd);

        $num = db('store_notice')->where(['wxapp_id'=>$wxapp_id,'is_see'=>0])->count();
        return $num;
    }

    public function newRedis(){
        $redis = new Redis();
        return $redis;
    }

}
